/*
 * @Description: 开放字段信息面板
 * @Author: Rfan
 * @Date: 2022-03-08 15:54:50
 * @LastEditTime: 2022-12-30 10:03:32
 */

import { useCallback, useEffect, useMemo, useState } from 'react';
import { Alert, Button, Space, Table, Tag } from 'antd';
import classNames from 'classnames/bind';
import update from 'immutability-helper';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { isNullObj } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import { useOpeningContext } from '../contexts/OpeningContext';
import DraggableBodyRow from '@/components/DraggableBodyRow';
import EditDialog from './dialogs/EditDialog';
import styles from '../styles/openingPane.module.scss';
import { EnumSortTypes } from '@/view/system/Opening/dictionaries';

const cx = classNames.bind(styles);

const { Column } = Table;

export type SortPaneProps = {
  title?: string;
  data?: any;
  type: 1 | 2;
};

const OpeningPane = (props: SortPaneProps) => {
  const { data, type } = props;
  const formatMessage = useFormatMessage();
  const {
    list,
    retrieveList,
    selectItems,
    setSelectKey,
    setList,
    getOpeningList,
    deleteOpeningFunc,
    visibleFilter,
    visibleColorFilter
  } = useOpeningContext();

  // 表格数据
  const [dataSource, setDataSource] = useState<any[]>([]);
  // 表格loading状态
  const [loading, setLoading] = useState<any>();
  // 表格请求参数
  const [listQuery, setListQuery] = useState<any>();
  // 选中的条目
  const [selectData, setSelectData] = useState();
  // 编辑弹窗展示状态
  const [editDialogVisible, setEditDialogVisible] = useState(false);

  useEffect(() => {
    // 根据开放字段类型设置表格数据
    if (type) {
      setDataSource(type === EnumSortTypes.Normal ? list : retrieveList);
    }
  }, [type, list, retrieveList]);

  useEffect(() => {
    // 设置请求参数
    setListQuery({ ...data, type });
  }, [data]);

  useEffect(() => {
    // 请求列表
    if (listQuery?.coordinate && !isNullObj(listQuery.coordinate)) {
      setLoading(true);
      getOpeningList(listQuery, type).finally(() => {
        setLoading(false);
      });
    }
  }, [listQuery]);

  /**
   * @description: 打开编辑弹窗
   * @param {any} record 选中的条目
   */
  const showEditDialog = (record: any): void => {
    setSelectData(record);
    setEditDialogVisible(true);
  };

  /**
   * @description: 设置选中的条目
   * @param {number} selectedKeys 选中条目的KEY
   */
  const onSelectChange = (selectedKeys: number[]): void => {
    setSelectKey(selectedKeys);
  };

  /**
   * @description: 列表选择配置
   */
  const rowSelection = {
    selectedRowKeys: selectItems,
    onChange: onSelectChange
  };

  /**
   * @description: 删除开放字段方法
   * @param {number} id 选中的条目ID
   */
  const delOpening = (id: number): void => {
    deleteOpeningFunc(id, '确认删除该开放字段？');
  };

  /**
   * 拖拽相关
   */
  const components = {
    body: {
      row: DraggableBodyRow
    }
  };

  const moveRow = useCallback(
    (dragIndex, hoverIndex) => {
      const dragRow = dataSource[dragIndex];
      console.log('move', dragRow);

      // 更新数据
      setList(
        update(dataSource, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragRow]
          ]
        }),
        type
      );
    },
    [dataSource]
  );

  return (
    <div className={cx('sort-pane')}>
      <div className={cx('tips')}>
        <Alert
          description="备注：调整排序可在表单内使用鼠标拖动“行”来实现；也可使用功能弹窗调整排序号（越小越靠前）"
          type="info"
          showIcon
          closable
        />
      </div>
      <div className={cx('container')}>
        <DndProvider backend={HTML5Backend}>
          <Table
            dataSource={dataSource}
            loading={loading}
            rowKey={(record) => record.rule.id}
            pagination={false}
            rowSelection={rowSelection}
            components={components}
            bordered
            onRow={(_record, index) =>
              ({
                index,
                moveRow
              } as any)
            }
          >
            <Column
              title="序号"
              dataIndex={['rule', 'id']}
              key="id"
              align="center"
              render={(_text, _record, index: number) => <span>{index + 1}</span>}
            />
            <Column title="排序" dataIndex={['rule', 'sortNo']} key="sortNo" align="center" />
            <Column
              title="字段名称"
              dataIndex={['field', 'field_desc']}
              key="fieldDesc"
              align="center"
            />
            <Column
              title="是否可见"
              dataIndex={['rule', 'visible']}
              key="visible"
              align="center"
              render={(text) => <Tag color={visibleColorFilter(text)}>{visibleFilter(text)}</Tag>}
            />
            <Column
              title={formatMessage('tableAction')}
              key="action"
              align="center"
              render={(_text, record: any) => (
                <Space>
                  <Button type="link" onClick={() => showEditDialog(record)}>
                    编辑
                  </Button>
                  <Button type="link" danger onClick={() => delOpening(record.rule.id)}>
                    删除
                  </Button>
                </Space>
              )}
            />
          </Table>
        </DndProvider>
      </div>

      {/* 编辑开放字段弹窗 */}
      {useMemo(
        () => (
          <EditDialog
            visible={editDialogVisible}
            data={selectData}
            onClose={() => {
              setEditDialogVisible(false);
            }}
          />
        ),
        [editDialogVisible]
      )}
    </div>
  );
};

export default OpeningPane;
